<?php

// 本类由系统自动生成，仅供测试用途
/**
 * AclAction
 * 
 * @package 
 * @author www.80boys.com
 * @copyright 2012
 * @version $Id$
 * @access public
 */
/**
 * AclAction
 * 
 * @package 
 * @author www.80boys.com
 * @copyright 2012
 * @version $Id$
 * @access public
 */
class AclAction extends CommonAction
{
    #用户列表
    public function userList()
    {
        //  header("Content-Type:text/html; charset=utf-8");
        //Vendor('Zend.Acl');
        //$acl = new Zend_Acl();
        //session('name','value');
        $list = M("User")->where(' id>1 and status = 1')->order('id DESC')->limit()->select();
        //var_dump($list);
        foreach ($list as $k => $v)
        {
            #获取角色列表
            $rolelist = M("role_user")->query("select ru.role_id,r.name from __TABLE__   ru LEFT 
        JOIN " . C('DB_PREFIX') .
                "role r  ON ru.role_id = r.id WHERE ru.user_id = " . $v['id']);
            #分割角色ID
            $str = '';
            foreach ($rolelist as $v)
            {
                $str .= $v['name'] . ",";
            }
            $list[$k]['role'] = $rolelist;
            $list[$k]['role_str'] = $str;
        }
        //print_r($list);
        $this->assign('list', $list);
        $this->display();
    }
    /*
    *添加用户
    */
    public function userAdd()
    {
        //echo self::$acl->isAllowed('6', 'testR') ? 'allowed' : 'denied';
        if($_POST['add'])
        {
            $arr = M('User')->where('username="' . trim($_POST['username']) . '"')->find();
            if($arr)
            {
                $this->error('用户已存在', U('Acl/userAdd'));
            }
            $data['username'] = $_POST['username'];
            $data['password'] = md5($_POST['password']);
            $insertid = M('User')->data($data)->add();
            $this->updateRolesU($insertid, $_POST['rolelist']);
            $this->success('添加成功', U('Acl/userlist'));
            $this->redirect('Acl/userlist', array(), 1, '添加成功...');
            exit();
        }
        $list = self::rolePlist();
        $this->assign('list', $list);
        $this->display('userAdd');
    }
    /*
    *编辑用户
    */
    public function userEdit()
    {
        if($_POST['add'])
        {
            $arr = M('User')->where('username="' . trim($_POST['username']) . '"')->find();
            $data['username'] = $_POST['username'];
            M('User')->where('id=' . (int)$_POST['id'])->save($data);
            $this->updateRolesU((int)$_POST['id'], $_POST['rolelist']);
            $this->success('编辑成功!', U('Acl/userlist'));
            exit();
        }
        $user = M('User')->where('id =' . (int)$_GET['id'])->find();
        $list = self::rolePlist();
        $clist =self::getRoleList($_GET['id'],'user');
        $this->assign('user', $user);
        $this->assign('list', $list);
        $this->assign('clist', $clist);
        $this->display();
    }
    /*
    *删除用户
    */
    public function userDel()
    {
        if(empty($_POST['ids']))
        {
            echo 0;
            exit;
        }
        $ids = $_POST['ids'];
        $data['status'] = 0;
        echo M('User')->where(" id in ( " . $ids . " )")->save($data) ? '1' : '0';
    }
    public function resList()
    {
        //  header("Content-Type:text/html; charset=utf-8");
        //Vendor('Zend.Acl');
        //$acl = new Zend_Acl();
        //session('name','value');
        $list = M("Resource")->order('id DESC')->limit()->select();
        //var_dump($list);
        //var_dump($list);
        foreach ($list as $k => $v)
        {
            //获取角色列表
            $rolelist = M("resource_role")->query("select ru.role_id,r.name from __TABLE__   ru LEFT 
        JOIN " . C('DB_PREFIX') .
                "role r  ON ru.role_id = r.id WHERE ru.resource_id = " . $v['id']);
            //分割角色ID
            $str = '';
            foreach ($rolelist as $v)
            {
                $str .= $v['name'] . ",";
            }
            $list[$k]['role'] = $rolelist;
            $list[$k]['role_str'] = $str;
        }
        $this->assign('list', $list);
        $this->display();
    }
    //添加资源
    public function resAdd()
    {
        if($this->_post('add'))
        {
            $arr = M('Resource')->where("name = '" . $this->_post('name') . "' ")->find();
            if($arr)
            {
                $this->error('资源已存在', U('Acl/resAdd'));
                exit();
            }
            $data['name'] = $this->_post('name');
            $data['description'] = $this->_post('description');
            $insertid = M('Resource')->data($data)->add();
            $this->updateRolesR($insertid, $_POST['rolelist']);
            $this->success('添加成功!', U('Acl/resList'));
            exit();
        }
        $list = self::rolePlist();
        $this->assign('list', $list);
        $this->display();
    }
    /*
    *编辑资源
    */
    public function resEdit()
    {
        if($this->_post('add'))
        {
            $data['name'] = $this->_post('name');
            $data['description'] = $this->_post('description');
            M('Resource')->where('id=' . $this->_post('id'))->save($data);
            $this->updateRolesR($this->_post('id'), $_POST['rolelist']);
            $this->success('更新成功!', U('Acl/reslist'));
            exit();
        }
        $resource = M('Resource')->where('id =' . $this->_get('id'))->find();
        $list = self::rolePlist();
        $clist =self::getRoleList($_GET['id'],'res');
        $this->assign('resource', $resource);
        $this->assign('list', $list);
        $this->assign('clist', $clist);
        $this->display();
    }
    /*
    *删除资源
    */
    public function resDel()
    {
        if(empty($_POST['ids']))
        {
            echo 0;
            exit;
        }
        $ids = $_POST['ids'];
        $bool = M('Resource')->where(" id in ( " . $ids . " )")->delete() ? '1' : '0';
        if($bool)
        {
            M('resource_role')->where(" resource_id in ( " . $ids . " )")->delete();
            echo '1';
        } else
        {
            echo '0';
        }
    }
    public function roleList()
    {
        //  header("Content-Type:text/html; charset=utf-8");
        //Vendor('Zend.Acl');
        //$acl = new Zend_Acl();
        //session('name','value');
        $list = M("Role")->order('id')->limit()->select();
        //var_dump($list);
        foreach ($list as $k => $v)
        {
            //获取角色列表
            $rolelist = M("role_priv")->query("select rp.priv_id,r.id,r.name,r.alias from __TABLE__   rp LEFT 
        JOIN " . C('DB_PREFIX') .
                "role r  ON rp.priv_id = r.id WHERE rp.role_id = " . $v['id']);
            //分割角色ID
            $str = '';
            foreach ($rolelist as $v)
            {
                $str .= $v['name'] . ",";
            }
            $list[$k]['role'] = $rolelist;
            $list[$k]['role_str'] = $str;
        }
        // print_r($this->admin);
        $this->assign('list', $list);
        $this->display();
    }
    /*
    *添加角色
    */
    public function roleAdd()
    {
        if($_POST['add'])
        {
            $arr = M('Role')->where('name="' . trim($_POST['name']) . '"')->find();
            if($arr)
            {
                $this->error('角色已存在', U('Acl/roleAdd'));
            }
            $data['name'] = $_POST['name'];
            $data['alias'] = $_POST['alias'];
            $insertid = M('Role')->data($data)->add();
            $this->updateRolesP($insertid, $_POST['rolelist']);
            $this->success('添加成功!', U('Acl/rolelist'));
            exit();
        }
        $list = self::rolePlist();
        $this->assign('list', $list);
        $this->display();
    }
    /*
    *编辑角色
    */
    public function roleEdit()
    {
        if($this->_post('add'))
        {
            $data['name'] = $this->_post('name');
            $data['alias'] = $this->_post('alias');
            M('Role')->where('id=' . $this->_post('id'))->save($data);
            $this->updateRolesP($this->_post('id'), $_POST['rolelist']);
            $this->success('更新成功!', U('Acl/rolelist'));
            exit();
        }
        $roles = M('Role')->where('id =' . $this->_get('id'))->find();
        $list = self::rolePlist();
        $clist =self::getRoleList($_GET['id'],'role');
        $this->assign('clist', $clist);
        $this->assign('list', $list);
        $this->assign('role', $roles);
        $this->display();
    }
    /*
    *删除角色
    */
    public function roleDel()
    {
        if(empty($_POST['ids']))
        {
            echo 0;
            exit;
        }
        $ids = $_POST['ids'];
        $bool = M('Role')->where(" id in ( " . $ids . " )")->delete() ? '1' : '0';
        if($bool)
        {
            M('role_user')->where(" role_id in ( " . $ids . " )")->delete();
            M('resource_role')->where(" role_id in ( " . $ids . " )")->delete();
            echo '1';
        } else
        {
            echo '0';
        }
    }
    // 更新用户角色表
    public function updateRolesU($id, $roles = array())
    {
        if($id)
        {
            M('role_user')->where('user_id=' . $id)->delete();
        } else
        {
            return false;
        }
        if($roles)
        {
            $vals = array();
            foreach ((array )$roles as $role)
            {
                $vals[] = array("user_id" => $id, "role_id" => $role);
            }
            foreach ($vals as $data)
            {
                M('role_user')->data($data)->add();
            }
            return true;
        } else
        {
            return false;
        }
    }
    // 更新资源角色表
    public function updateRolesR($id, $roles = array())
    {
        if($id)
        {
            M('resource_role')->where('resource_id =' . $id)->delete();
        } else
        {
            return false;
        }
        if($roles)
        {
            $vals = array();
            foreach ((array )$roles as $role)
            {
                $vals[] = array("resource_id" => $id, "role_id" => $role);
            }
            foreach ($vals as $data)
            {
                M('resource_role')->data($data)->add();
            }
            return true;
        } else
        {
            return false;
        }
    }
    // 更新角色权限表
    public function updateRolesP($id, $roles = array())
    {
        if($id)
        {
            M('role_priv')->where('role_id =' . $id)->delete();
        } else
        {
            return false;
        }
        if($roles)
        {
            $vals = array();
            foreach ((array )$roles as $role)
            {
                $vals[] = array("role_id" => $id, "priv_id" => $role);
            }
            foreach ($vals as $data)
            {
                M('role_priv')->data($data)->add();
            }
            return true;
        } else
        {
            return false;
        }
    }
    public function appList()
    {
        #顶级菜单列表
        $applist = M("App")->where(' app_depth = 1 ')->order('app_id ASC')->limit()->
            select();
        #二级菜单列表
        foreach ($applist as $k => $v)
        {
            $list2 = M("App")->where(' app_depth = 2 AND app_fid = ' . $v['app_id'] . ' ')->
                order('app_id ASC')->limit()->select();
            $applist[$k]['items'] = $list2;
        }
        #三级菜单列表
        foreach ($applist as $k => $v)
        {
            foreach ($v['items'] as $kk => $vv)
            {
                $list3 = M("App")->where(' app_depth = 3 AND app_fid = ' . $vv['app_id'] . ' ')->
                    order('app_id ASC')->limit()->select();
                $applist[$k]['items'][$kk]['items'] = $list3;
            }
        }
        #角色赋值字段
        foreach ($applist as $k => $v)
        {
            $applist[$k]['role_str'] = $this->getrole($v['app_role']);
            foreach ($v['items'] as $kk => $vv)
            {
                $applist[$k]['items'][$kk]['role_str'] = $this->getrole($vv['app_role']);
                foreach ($vv['items'] as $kkk => $vvv)
                {
                    $applist[$k]['items'][$kk]['items'][$kkk]['role_str'] = $this->getrole($vvv['app_role']);
                }
            }
        }
        //print_r($applist);
        $this->assign('list', $applist);
        $this->display();
    }
    #添加菜单
    public function appAdd()
    {
        if($_POST['add'])
        {
            $data['app_name'] = $_POST['app_name'];
            $data['app_url'] = $_POST['app_url'];
            $data['app_fid'] = $_POST['app_fid'];
            $data['app_role'] = implode(',', $_POST['rolelist']);
            if($_POST['app_fid'] == 0)
            {
                $data['app_depth'] = 1;
            } else
            {
                if($_POST['type'] == 1)
                {
                    $data['app_depth'] = 2;
                }
                if($_POST['type'] == 2)
                {
                    $data['app_depth'] = 3;
                }
            }
            $insertid = M('App')->data($data)->add();
            $this->success('更新成功!', U('Acl/appList'));
            exit();
        }
        #顶级菜单列表
        $applist = M("App")->where(' app_depth = 1 ')->order('app_id ASC')->limit()->
            select();
        $list = self::rolePlist();
        $this->assign('list', $list);
        #二级菜单列表
        foreach ($applist as $k => $v)
        {
            $list2 = M("App")->where(' app_depth = 2 AND app_fid = ' . $v['app_id'] . ' ')->
                order('app_id ASC')->limit()->select();
            $applist[$k]['items'] = $list2;
        }
        #三级菜单列表
        foreach ($applist as $k => $v)
        {
            foreach ($v['items'] as $kk => $vv)
            {
                $list3 = M("App")->where(' app_depth = 3 AND app_fid = ' . $vv['app_id'] . ' ')->
                    order('app_id ASC')->limit()->select();
                $applist[$k]['items'][$kk]['items'] = $list3;
            }
        }
        $this->assign('applist', $applist);
        $this->display();
    }
    #编辑菜单
    public function appEdit()
    {
        if($this->_post('add'))
        {
            $data['app_id'] = $this->_post('app_id');
            $data['app_name'] = $this->_post('app_name');
            $data['app_url'] = $this->_post('app_url');
            $data['app_role'] = implode(',', $_POST['rolelist']);
            M('App')->save($data);
            $this->success('更新成功!', U('Acl/applist'));
            exit();
        }
        $list = self::rolePlist();
        $app = M('App')->where('app_id =' . $this->_get('id'))->field('*')->find();
        $clist = M("Role")->where('id in ('.$app['app_role'].') ')->order('id')->limit()->select();
        $this->assign('list', $list);
        $this->assign('clist', $clist);
        $this->assign('app', $app);
        $this->display();
    }
    #获取ROLE 角色
    public function getrole($ids)
    {
        $str = '';
        $list = M("Role")->where(' id in(' . $ids . ')')->order('id')->limit()->select();
        foreach ($list as $k => $v)
        {
            $str .= $v['name'] . ",";
        }
        return $str;
    }
    #默认获取角色列表
    private function rolePlist(){

        $user = session('_LOGIN_');
        foreach ($user['rolelist'] as $k => $v)
        {
            $str .= $v['role_id'] . ",";
        };

        if($user['id'] != 1){
                 $privlist = M("role_priv")->query("select r.* from __TABLE__   ru  
                 LEFT JOIN ". C('DB_PREFIX') ."role r ON ru.priv_id = r.id WHERE ru.role_id in (".substr($str, 0,-1).") ");
        }else{

               $privlist =  $list = M("Role")->where('')->order('id')->limit()->select();
        }

        return  $privlist;

    }
    #编辑获取角色列表
    private function getRoleList($id= 0,$type = 'user'){
        if($id && $type == 'user'){
                 $privlist = M("role_user")->query("select r.* from __TABLE__   ru  
                 LEFT JOIN ". C('DB_PREFIX') ."role r ON ru.role_id = r.id WHERE ru.user_id = {$id} ");
        }
        if($id && $type == 'role'){
                 $privlist = M("role_priv")->query("select r.* from __TABLE__   ru  
                 LEFT JOIN ". C('DB_PREFIX') ."role r ON ru.priv_id = r.id WHERE ru.role_id = {$id} ");
        }
        if($id && $type == 'res'){
                 $privlist = M("resource_role")->query("select r.* from __TABLE__   ru  
                 LEFT JOIN ". C('DB_PREFIX') ."role r ON ru.role_id = r.id WHERE ru.resource_id = {$id} ");
        }
        return  $privlist;

    }
}
